<!-- 洁净室环境检测-PARTICLE -->
<template>
  <div>
    <div v-if="showCharts && !equipopenDetail" class="page-chart">
      <testTypeTrend title="Particle检测指标累计趋势" type="Particle" :chartParams="queryParams" @reset="resetTable" />
    </div>

    <div class="page-contain">
      <px-form v-show="showSearch" ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
        <px-form-item label="记录编号">
          <px-input v-model="queryParams.detectCode" placeholder="请输入记录编号" clearable />
        </px-form-item>
        <px-form-item label="检测结果">
          <px-select v-model="queryParams.detectResultSummary" placeholder="请选择检测结果" clearable filterable>
            <px-option v-for="item in resultList" :key="item.value" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
        <px-form-item label="检测单位" prop="detectOrganization">
          <px-select v-model="queryParams.detectOrganization" placeholder="请输入检测单位" clearable filterable>
            <px-option v-for="dict in organizationArr" :key="dict.itemValue" :label="dict.itemName" :value="dict.itemValue" />
          </px-select>
        </px-form-item>
        <px-form-item label="区域">
          <px-select v-model="queryParams.areaCode" placeholder="请选择区域" clearable filterable @change="areaChange">
            <px-option v-for="dict in areaList" :key="dict.itemValue" :label="dict.itemName" :value="dict.itemValue" />
          </px-select>
        </px-form-item>
        <px-form-item label="取样点">
          <px-select
            v-model="queryParams.multipleLocation"
            collapse-tags
            collapse-tags-tooltip
            placeholder="请选择取样点"
            multiple
            clearable
            filterable
          >
            <px-option v-for="dict in areaLiquidList" :key="dict.value" :label="dict.label" :value="dict.value" />
          </px-select>
        </px-form-item>
        <!-- <px-form-item label="取样人"> -->
        <!-- <px-input v-model="queryParams.samplePerson" placeholder="请输入取样人" clearable /> -->
        <!-- <px-select v-model="queryParams.samplePersonId" filterable clearable placeholder="请选择取样人" @change="samplePersonIdChange"> -->
        <!-- <px-option v-for="item in peopleList" :key="item.value" :label="item.label" :value="item.value" /> -->
        <!-- </px-select> -->
        <!-- </px-form-item> -->
        <px-form-item label="取样日期" style="width: 516px">
          <px-date-picker
            v-model="dateRange"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            :default-time="defaultTime"
          />
        </px-form-item>
        <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery('search')">搜索</px-button>
        <px-button style="margin-top: -17px" icon="" @click="resetQuery">重置</px-button>
      </px-form>

      <px-row :gutter="10" class="mb8">
        <!-- <px-col :span="1.5">
          <px-button type="primary" icon="" @click="handleUpload">导入</px-button>
        </px-col> -->
        <!-- <px-col :span="1.5">
          <px-button type="primary" icon="" @click="handleAdd">新增</px-button>
        </px-col> -->
        <px-col :span="1.5">
          <px-button v-has="'Particle_BATCH_EXPORT'" type="primary" plain icon="" @click="handleExport">批量下载</px-button>
        </px-col>

        <!-- <px-col :span="1.5">
          <px-button v-has="'CommonEquipListDelete'" type="danger" plain icon="" :disabled="multiple" @click="handleDelete">删除</px-button>
        </px-col> -->
      </px-row>

      <px-table
        v-if="!equipopen && !equipopenDetail"
        v-loading="loading"
        :data="typeList"
        height="calc(100vh - 329px)"
        show-overflow-tooltip
        border
        @selection-change="handleSelectionChange"
      >
        <px-table-column type="selection" width="40" />
        <px-table-column label="记录编号" align="center" prop="detectCode" min-width="160" />
        <!-- <px-table-column label="取样日期" width="130" prop="sampleDate">
          <template #default="scope">
            <span>{{ scope.row.sampleDate ? scope.row.sampleDate : "-" }}</span>
          </template>
        </px-table-column> -->
        <px-table-column label="检测结果" width="90" prop="drainageTime">
          <template #default="scope">
            <px-tag v-if="scope.row.detectResultSummary" :type="scope.row.detectResultSummary === '合格' ? 'success' : 'danger'" effect="dark">
              {{ scope.row.detectResultSummary }}
            </px-tag>
          </template>
        </px-table-column>
        <px-table-column label="区域" width="100" prop="areaName" />
        <px-table-column label="取样点" width="100" prop="sampleLocation">
          <template #default="scope">
            <span>{{ getName(scope.row.sampleLocation) || "-" }}</span>
          </template>
        </px-table-column>
        <px-table-column label="取样时间" prop="sampleTime" width="160">
          <template #default="scope">
            <span>{{ scope.row.sampleTime ? scope.row.sampleTime : "-" }}</span>
          </template>
        </px-table-column>
        <px-table-column label="取样人" prop="samplePerson" min-width="100">
          <template #default="scope">
            <span>{{ scope.row.samplePerson == null || scope.row.samplePerson.includes("null") ? "N/A" : scope.row.samplePerson }}</span>
          </template>
        </px-table-column>
        <px-table-column
          v-for="(item, index) in tableColumns"
          :key="item.key"
          :props="item.itemName"
          :label="`${item.itemName}${item.controlValue}`"
          width="150"
        >
          <template #default="scope">
            <span :style="{ color: scope.row.testResult[index].ooc ? '#ef4444' : '' }">{{
              scope.row.testResult[index].testValue ? scope.row.testResult[index].testValue : "-"
            }}</span>
          </template>
        </px-table-column>
        <px-table-column fixed="right" label="操作" align="center" width="200">
          <template #default="scope">
            <px-button v-has="'Particle_VIEW'" link type="primary" @click="handleDetail(scope.row.id)">
              <px-tooltip class="box-item" content="详情" placement="top">
                <px-icon>
                  <Tickets />
                </px-icon> </px-tooltip
            ></px-button>
            <!-- <px-button v-has="'Particle_EDIT'" v-if="scope.row.status != 'INVALID'" link type="primary" @click="handleEditor(scope.row.id)">
              <px-tooltip class="box-item" content="编辑" placement="top">
                <px-icon>
                  <EditPen />
                </px-icon> </px-tooltip
            ></px-button> -->
            <!-- <px-button v-if="scope.row.status != 'INVALID'" v-has="'Particle_DELETE'" link type="danger" @click="handleDelete(scope.row)"
              ><px-tooltip class="box-item" content="删除" placement="top">
                <px-icon>
                  <Delete />
                </px-icon> </px-tooltip
            ></px-button> -->
            <!-- <px-button link type="primary"
              ><px-tooltip class="box-item" content="归档" placement="top">
                <px-icon><Files /></px-icon> </px-tooltip
            ></px-button> -->
          </template>
        </px-table-column>
        <template #empty>
          <px-empty :image-size="150" />
        </template>
      </px-table>

      <pagination
        v-if="!equipopen && !equipopenDetail"
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        style="margin-bottom: -10px"
        :total="total"
        @pagination="getList"
      />

      <!-- 添加或修改参数配置对话框 -->

      <px-scrollbar v-if="equipopen" class="editorEquip">
        <px-button style="margin-left: 24px" type="primary" :icon="ArrowLeft" @click="cancel">返回</px-button>
        <div class="px-descriptions__title" style="margin: 20px 0 0 20px">基本信息</div>
        <px-row style="padding: 20px">
          <px-col :span="8">
            <px-descriptions class="margin-top" :column="1" border>
              <px-descriptions-item>
                <template #label>
                  <div class="cell-item">记录编号:</div>
                </template>
                {{ equipdata.detectCode }}
              </px-descriptions-item>
              <px-descriptions-item>
                <template #label>
                  <div class="cell-item">区域:</div>
                </template>
                {{ equipdata.areaName }}
              </px-descriptions-item>
              <px-descriptions-item>
                <template #label>
                  <div class="cell-item">取样人:</div>
                </template>
                {{ equipdata.samplePerson }}
              </px-descriptions-item>
            </px-descriptions>
          </px-col>
          <px-col :span="8">
            <px-descriptions class="center2" :column="1" border>
              <px-descriptions-item>
                <template #label>
                  <div class="cell-item">取样时间:</div>
                </template>
                {{ equipdata.sampleTime }}
              </px-descriptions-item>
              <px-descriptions-item>
                <template #label>
                  <div class="cell-item">取样点:</div>
                </template>
                {{ getName(equipdata.sampleLocation) }}
              </px-descriptions-item>
              <!-- <px-descriptions-item>
                <template #label>
                  <div class="cell-item">排水量(m³):</div>
                </template>
                {{ equipdata.drainageVolume }}
              </px-descriptions-item> -->
              <!-- <px-descriptions-item>
                <template #label>
                  <div class="cell-item">本科负责人:</div>
                </template>
                {{ equipdata.responsiblePerson }}
              </px-descriptions-item> -->
            </px-descriptions>
          </px-col>
        </px-row>

        <div style="width: 100%; padding: 0 0 0 20px; clear: both">
          <div class="px-descriptions__title" style="padding: 20px 0">取样照片</div>
          <PhotoUpload photoType="view" :photoData="{ moduleName: 'GENERAL_CHEMICALS' }" :photoList="equipdata.samplingPhoto" />
        </div>
        <div style="width: 100%; padding: 0 20px 20px; clear: both">
          <div class="px-descriptions__title" style="padding: 20px 0">附件</div>
          <FileUpload fileType="view" :fileData="{ moduleName: 'GENERAL_CHEMICALS' }" :fileList="equipdata.detectReportAttachment" />
        </div>
        <div style="width: 100%; padding: 0 20px 20px; clear: both">
          <div class="px-descriptions__title" style="padding: 20px 0">检测项目</div>
          <div class="tableTop">
            <div class="topList">检测项目</div>
            <div v-for="item in equipdata.testItems" :key="item.key" class="topList">{{ item.itemName }}</div>
          </div>
          <div class="tableMain">
            <div class="topList">内控指标</div>
            <div v-for="item in equipdata.testItems" :key="item.key" class="topList">{{ item.controlValue }}</div>
          </div>
          <div class="tableMain">
            <div class="topList">检测结果</div>
            <div v-for="(value, key) in equipdata.testResult" :key="key" class="topList">
              {{ equipdata.testResult[key] }}
            </div>
          </div>
          <div class="tableMain">
            <div class="topList">分析</div>
            <div v-for="item in equipdata.testItems" :key="item.key" class="topList">
              <px-button :type="item.testBtn ? 'success' : 'info'" @click="analyze(equipdata.testItems, item)">{{ item.itemName }}分析</px-button>
            </div>
          </div>
        </div>
        <!-- <div class="btmContent">
          <div>
            <px-date-picker
              v-model="dateRangeCharts"
              type="datetimerange"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              :default-time="defaultTime"
            />
          </div>
          <div class="queryBtn">
            <px-button type="primary" icon="" @click="handleQueryCharts('search')">分析</px-button>
            <px-button icon="" @click="resetQueryCharts">重置</px-button>
          </div>
        </div> -->
        <div v-if="equipopen" class="btn_box">
          <barTitle title="Q部门 VS online检测" />
          <div class="btn_chart">
            <div class="chart_item">
              <!-- <lineChart ref="barChartsRef" :key="echartsKey" :labelLayoutFn="labelLayoutBarFn" :width="600" :height="480" /> -->
              <div v-show="showBarCharts" ref="barChartsRef" style="width: 100%; min-width: 600px; height: 480px; border: 1px solid #dcdcdc" />
              <div v-show="!showBarCharts" class="echarts-empty">
                <px-empty :image-size="100" />
              </div>
            </div>
            <div v-if="currentBar !== 'Q部门'" class="chart_item">
              <!-- <lineChart ref="spcChartsRef" :labelLayoutFn="labelLayoutLineFn" :width="600" :height="480" /> -->
              <spcCharts
                v-show="Object.keys(spcOptions).length"
                ref="spcChartsDom"
                :key="midKey"
                :width="600"
                :height="480"
                :optionData="spcOptions"
                color="#3B82F6"
              />
              <div v-show="!Object.keys(spcOptions).length" class="echarts-empty1">
                <px-empty :image-size="100" />
              </div>
            </div>
            <div v-if="currentBar === 'Q部门'" class="chart_item" style="border: 1px solid #dcdcdc">
              <barCom v-show="Object.keys(costOptions).length" :key="tablePieKey" :width="600" :height="200" :options="costOptions" />
              <div v-show="!Object.keys(costOptions).length" class="echarts-empty1">
                <px-empty :image-size="100" />
              </div>
            </div>
          </div>
        </div>
      </px-scrollbar>
      <px-scrollbar v-if="equipopenDetail" class="addEquip">
        <px-button style="margin-left: 24px" type="primary" :icon="ArrowLeft" @click="equipopenDetailcancel">返回</px-button>
        <px-form
          ref="detailruleFormRef"
          :disabled="fromdisable"
          :rules="rules"
          :model="equipdata"
          :inline="true"
          class="demo-form-inline"
          label-width="160px"
        >
          <div
            class="box-card1"
            :style="{
              height: jibenxinxiFlg == true ? '' : '42px'
            }"
          >
            <div class="card-header" @click="setqingdanFlg()">
              <div class="card-title">基本信息</div>
              <div class="card-main">
                <px-icon v-if="!jibenxinxiFlg">
                  <ArrowDown />
                </px-icon>
                <px-icon v-else>
                  <ArrowUp />
                </px-icon>
              </div>
            </div>
            <div class="form-div">
              <px-row>
                <px-col :span="8">
                  <px-form-item label="记录编号">
                    <px-input v-model="equipdata.detectCode" disabled="true" placeholder="记录编号为系统生成" clearable /> </px-form-item
                ></px-col>
                <px-col :span="8">
                  <px-form-item label="取样时间" prop="sampleTime">
                    <px-date-picker
                      v-model="equipdata.sampleTime"
                      style="width: calc(100% - 100px)"
                      placeholder="请选择入库日期"
                      type="datetime"
                      format="YYYY-MM-DD HH:mm:ss"
                      value-format="YYYY-MM-DD HH:mm:ss"
                      @change="checkTime"
                    />
                  </px-form-item>
                </px-col>
                <px-col :span="8">
                  <px-form-item label="检测机构">
                    <px-select v-model="equipdata.detectOrganization" clearable filterable placeholder="请选择检测机构">
                      <px-option v-for="item in organizationArr" :key="item.itemValue" :label="item.itemName" :value="item.itemValue" />
                    </px-select>
                  </px-form-item>
                </px-col>
              </px-row>
              <px-row>
                <px-col :span="8">
                  <px-form-item label="检测结果">
                    <px-select v-model="equipdata.detectResultSummary" placeholder="请选择检测结果" clearable filterable>
                      <px-option v-for="item in resultList" :key="item.value" :label="item.name" :value="item.value" />
                    </px-select>
                  </px-form-item>
                </px-col>
                <!-- <px-col :span="8">
                  <px-form-item label="报告编号">
                    <px-input v-model="equipdata.reportNumber" placeholder="请输入报告编号" clearable />
                  </px-form-item>
                </px-col>
                <px-col :span="8">
                  <px-form-item label="本科负责人" prop="responsiblePersonId">
                    <px-select
                      v-model="equipdata.responsiblePersonId"
                      filterable
                      clearable
                      placeholder="请选择本科负责人"
                      @change="responsiblePersonIdChange"
                    >
                      <px-option v-for="item in peopleList" :key="item.value" :label="item.label" :value="item.value" />
                    </px-select>
                  </px-form-item>
                </px-col> -->
                <px-col :span="8">
                  <px-form-item label="取样点" prop="location">
                    <px-select v-model="equipdata.location" placeholder="请选择取样点" style="width: calc(100% - 100px)" clearable filterable>
                      <px-option v-for="dict in liquidList" :key="dict.id" :label="dict.itemName" :value="dict.itemValue" />
                    </px-select>
                  </px-form-item>
                </px-col>
                <px-col :span="8">
                  <px-form-item label="取样人" prop="samplePersonId">
                    <px-select v-model="equipdata.samplePersonId" filterable clearable placeholder="请选择取样人" @change="samplePersonIdChange1">
                      <px-option v-for="item in peopleList" :key="item.value" :label="item.label" :value="item.value" />
                    </px-select>
                  </px-form-item>
                </px-col>
              </px-row>
              <!-- <px-row>
                <px-col :span="8">
                  <px-form-item label="取样点" prop="location">
                    <px-select v-model="equipdata.location" placeholder="请选择取样点" style="width: calc(100% - 100px)" clearable filterable>
                      <px-option v-for="dict in liquidList" :key="dict.id" :label="dict.itemName" :value="dict.itemValue" />
                    </px-select>
                  </px-form-item>
                </px-col>
                <px-col :span="8">
                  <px-form-item label="取样人" prop="samplePersonId">
                    <px-select v-model="equipdata.samplePersonId" filterable clearable placeholder="请选择取样人" @change="samplePersonIdChange1">
                      <px-option v-for="item in peopleList" :key="item.value" :label="item.label" :value="item.value" />
                    </px-select>
                  </px-form-item>
                </px-col>
              </px-row> -->
            </div>
          </div>

          <div
            class="box-card2"
            :style="{
              height: jiqicanshuFlg == true ? '' : '42px'
            }"
          >
            <div class="card-header" @click="setjiqicanshuFlg()">
              <div class="card-title">取样照片</div>
              <div class="card-main">
                <px-icon v-if="!jiqicanshuFlg">
                  <ArrowDown />
                </px-icon>
                <px-icon v-else>
                  <ArrowUp />
                </px-icon>
              </div>
            </div>
            <px-scrollbar class="form-div">
              <div class="info-form-content">
                <PhotoUpload
                  :key="'ptoto1'"
                  photoType="add"
                  :photoData="{ moduleName: 'GENERAL_CHEMICALS' }"
                  :photoList="equipdata.samplingPhoto"
                  @changePhotoList="changePhotoList1"
                  @savePhotoStatus="savePhotoStatus1"
                />
              </div>
            </px-scrollbar>
          </div>
          <div
            class="box-card3"
            :style="{
              height: shebeitaizhangFlg == true ? '' : '42px'
            }"
          >
            <div class="card-header" @click="setshebeitaizhangFlg()">
              <div class="card-title">附件</div>
              <div class="card-main">
                <px-icon v-if="!shebeitaizhangFlg">
                  <ArrowDown />
                </px-icon>
                <px-icon v-else>
                  <ArrowUp />
                </px-icon>
              </div>
            </div>
            <px-scrollbar class="form-div">
              <div class="info-form-content">
                <FileUpload
                  fileType="add"
                  :fileData="{ moduleName: 'GENERAL_CHEMICALS' }"
                  :fileList="equipdata.detectReportAttachment"
                  @changeFileList="changeFileList"
                  @saveFileStatus="saveFileStatus"
                />
              </div>
            </px-scrollbar>
          </div>
          <div
            class="box-card2"
            :style="{
              height: moxingshezhiFlg == true ? '' : '42px'
            }"
          >
            <div class="card-header" @click="setmoxingshezhiFlg()">
              <div class="card-title">检测项目</div>
              <div class="card-main">
                <px-icon v-if="!moxingshezhiFlg">
                  <ArrowDown />
                </px-icon>
                <px-icon v-else>
                  <ArrowUp />
                </px-icon>
              </div>
            </div>
            <px-scrollbar class="form-div">
              <div class="info-form-content">
                <div v-if="buttonTitle == '新增'">
                  <div class="tableTop">
                    <div class="topList">检测项目</div>
                    <div v-for="item in waterTestList" :key="item.key" class="topList">{{ item.itemName }}</div>
                  </div>
                  <div class="tableMain">
                    <div class="topList">内控指标</div>
                    <div v-for="item in waterTestList" :key="item.key" class="topList">{{ item.controlValue }}</div>
                  </div>
                  <div class="tableMain">
                    <div class="topList">检测结果</div>
                    <!-- {{ equipdata.testResult }} -->
                    <div v-for="(value, key) in equipdata.testResult" :key="key" class="topList">
                      <px-input v-model="equipdata.testResult[key]" clearable />
                    </div>
                  </div>
                </div>
                <div v-if="buttonTitle == '编辑'">
                  <div class="tableTop">
                    <div class="topList">检测项目</div>
                    <div v-for="item in equipdata.testItems" :key="item.key" class="topList">{{ item.itemName }}</div>
                  </div>
                  <div class="tableMain">
                    <div class="topList">内控指标</div>
                    <div v-for="item in equipdata.testItems" :key="item.key" class="topList">{{ item.controlValue }}</div>
                  </div>
                  <div class="tableMain">
                    <div class="topList">检测结果</div>
                    <div v-for="(value, key) in equipdata.testResult" :key="key" class="topList">
                      <px-input v-model="equipdata.testResult[key]" clearable />
                    </div>
                  </div>
                </div>
              </div>
            </px-scrollbar>
          </div>
        </px-form>
      </px-scrollbar>
      <div v-if="equipopenDetail" class="px-dialog-footer">
        <px-button @click="equipopenDetailcancel">取消</px-button>
        <px-button v-if="fromdisable" type="primary" @click="equipopenDetailcancel">关闭</px-button>
        <px-button v-else type="primary" :disabled="photoStatusFlag || fileStatusFlag" @click="equipopenDetailsubmitForm(detailruleFormRef)"
          >保存</px-button
        >
      </div>
    </div>

    <px-dialog v-model="progressVisible" title="上传进度" width="30%" center align-center>
      <px-progress :percentage="Math.floor(progressPercent)" />
    </px-dialog>
    <uploadFiles v-if="dialogVisible" v-model="dialogVisible" detectCategory="PARTICLE" @submit="submitHandler" />
    <px-dialog v-model="historyDialogVisible" width="60%" title="导入历史" align-center>
      <px-table :data="historyData" border class="inspection-table">
        <px-table-column label="序号" type="index" width="80" />
        <px-table-column prop="originalName" label="文件名称" show-overflow-tooltip />
        <px-table-column prop="createTime" label="Date" width="180" />
        <px-table-column label="操作" align="center" width="80">
          <template #default="scope">
            <px-tooltip content="下载" placement="top">
              <px-button link type="primary" icon="Download" @click="handleDownload(scope.row)" />
            </px-tooltip>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-show="historytotal > 0"
        v-model:page="historyPageNum"
        v-model:limit="historyPageSize"
        style="margin-bottom: -10px"
        :total="historytotal"
        @pagination="getHistoryList"
      />
    </px-dialog>
  </div>
</template>

<script setup lang="ts">
import Doc from "@/assets/svg/file/doc.svg?component";
import Pdf from "@/assets/svg/file/pdf.svg?component";
import Ppt from "@/assets/svg/file/ppt.svg?component";
import Txt from "@/assets/svg/file/txt.svg?component";
import Xsl from "@/assets/svg/file/xsl.svg?component";
import { ArrowLeft } from "@px-ui/icons-vue";
import uploadFiles from "../components/uploadFiles/index.vue";
import { useRoute } from "vue-router";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, ref, toRefs, reactive, onMounted, nextTick, markRaw, computed } from "vue";
import { getToken } from "@/utils/auth";
import type { UtilsEChartsOption } from "@pureadmin/utils";
import * as echarts from "echarts";
import { spcquerySpcAnalysis } from "@/api/spc";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import FileUpload from "@/components/Upload/FileUpload.vue";
import spcCharts from "@/views/machine/components/spcCharts/index.vue";
import barCom from "@/views/common/energy/components/barCom/index.vue";
import { queryChildByTypeCodeAndItemValue, liquidFileDelete } from "@/api/machineClass";
import { generalqueryListPage, generalqueryDetail, generalqueryadd, generalquerydeleted, generalqueryupdate } from "@/api/chemicals";
import testTypeTrend from "@/views/machine/operation/environmentTestManage/components/testTypeTrend/index.vue";
import {
  wasteWaterqueryListPage0,
  wasteWatergetTestItem0,
  wasteWateradd0,
  wasteWaterqueryDetail0,
  wasteWaterupdate0,
  wasteWaterdelete0,
  getReadersInZoneByType,
  queryImportHistoryList,
  importAddAmc,
  getBarChartsData
} from "@/api/machineClass";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { querySpecValues, getDetectedValuesInPair, queryQCheck } from "@/api/machineApi";

const currentBar = ref("Q部门");

const options = [
  {
    itemValue: "system1",
    itemName: "系统1"
  },
  {
    itemValue: "system2",
    itemName: "系统2"
  }
];
const historyDialogVisible = ref(false);
const showCharts = ref(false);
const historyData = ref([]);
const historyPageNum = ref(1);
const historyPageSize = ref(10);
const historytotal = ref(0);

const tablePieKey = ref(Date.now());

const costOptions = ref({});

const peopleList = ref<any>([]);

const samplePersonIdChange = (val: any) => {
  queryParams.value.samplePerson = peopleList.value.filter((item: any) => item.value === val)[0].label;
};
const samplePersonIdChange1 = (val: any) => {
  equipdata.value.samplePerson = peopleList.value.filter((item: any) => item.value === val)[0].label;
};
const responsiblePersonIdChange = (val: any) => {
  equipdata.value.responsiblePerson = peopleList.value.filter((item: any) => item.value === val)[0].label;
};

const getHistoryList = async () => {
  const data = await queryImportHistoryList({ pageNum: historyPageNum.value, pageSize: historyPageSize.value });
  historyData.value = data?.data;
  historytotal.value = data?.total;
};

const handleDownload = (row: any) => {
  // 下载文件
  console.log(row.originalName);
  const url = row.fileUrl;
  const link = document.createElement("a");
  link.href = url;
  link.setAttribute("download", row.originalName);
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

const dateRangeCharts = ref([]);
const resultList = [
  // {
  //   name: "全部",
  //   value: "0"
  // },
  {
    name: "合格",
    value: "1"
  },
  {
    name: "不合格",
    value: "0"
  }
];
const jibenxinxiFlg = ref(true);
const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)];
const setqingdanFlg = () => {
  jibenxinxiFlg.value = !jibenxinxiFlg.value;
};
const jiqicanshuFlg = ref(true);
const setjiqicanshuFlg = () => {
  jiqicanshuFlg.value = !jiqicanshuFlg.value;
};
const shebeitaizhangFlg = ref(true);
const setshebeitaizhangFlg = () => {
  shebeitaizhangFlg.value = !shebeitaizhangFlg.value;
};
const moxingshezhiFlg = ref(true);
const setmoxingshezhiFlg = () => {
  moxingshezhiFlg.value = !moxingshezhiFlg.value;
};

const route = useRoute();

const organizationArr = ref([]);

const getName = val => {
  const arr = liquidList.value.filter(el => el.itemValue === val);
  if (arr && arr.length) {
    return arr[0].itemName || val;
  } else {
    return val;
  }
};

const areaList = ref([]);

const areaChange = val => {
  queryParams.value.multipleLocation = [];
};

const areaLiquidList = computed(() => {
  if (!queryParams.value.areaCode) {
    return [];
  } else {
    const area: any = areaList.value.find(e => e.itemValue === queryParams.value.areaCode);
    const str: string = JSON.parse(area.itemDesc.replace(/[\r|\n|\t]/g, "")).points;
    return str.split(",").map(e => {
      return {
        value: e,
        label: e
      };
    });
  }
});

onMounted(async () => {
  await getqueryCategoryList();
  const data: any = await queryChildByTypeCodeAndItemValue({
    value: "CSP01",
    typeCode: "MCTS"
  });
  const areaData: any = await queryChildByTypeCodeAndItemValue({
    value: "CLEAN_ROOM_AREA",
    typeCode: "MCTS"
  });
  areaList.value = areaData;
  liquidList.value = data;
  await getList();
  peopleList.value = await getEmployeeIdAndName(["MACHINE"]);
  queryChildByTypeCodeAndItemValue({
    value: "DU01",
    typeCode: "MCTS"
  }).then((res: any) => {
    organizationArr.value = res ? res : [];
  });
  if (route.query.equipmentId) {
    handleDetail(route.query.equipmentId);
  }
  showCharts.value = true;
});
const { proxy }: any = getCurrentInstance();

const typeList = ref([]);
const detailruleFormRef = ref();
const progressVisible = ref(false);
const open = ref(false);
const equipopen = ref(false);
const equipopenDetail = ref(false);
const fromdisable = ref(false);
const loading = ref(true);
const showBarCharts = ref(false);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const typeIdloading = ref(false);
const total = ref(0);
const progressPercent = ref(0);
const title = ref("");
const dateRange = ref([
  proxy.parseTime(new Date().getTime() - 30 * 24 * 60 * 60 * 1000 + 1000, "{y}-{m}-{d} {h}:{i}:{s}"),
  proxy.parseTime(new Date().getTime(), "{y}-{m}-{d} {h}:{i}:{s}")
]);
const dialogVisible = ref(false);

// 图片是否上传完，是否可以保存
const savePhotoStatus1 = val => {
  console.log(val);
  photoStatusFlag.value = val;
};
const savePhotoStatus2 = val => {
  photoStatusFlag.value = val;
};
const savePhotoStatus3 = val => {
  photoStatusFlag.value = val;
};
const savePhotoStatus4 = val => {
  photoStatusFlag.value = val;
};
// 文件是否上传完，是否可以保存
const saveFileStatus = val => {
  fileStatusFlag.value = val;
};

const waterstatusList = [
  {
    value: "VALID",
    name: "全部"
  },
  {
    value: "INVALID",
    name: "已删除"
  }
];
const buttonTitle = ref("");
const testList = ref([]);
const data = reactive({
  liquidList: [],
  typeIdList: [],
  categoryList: [],
  equipmentTypeList: [],
  positionList: [],
  equipmentDeptList: [],
  modelIdList: [],
  form: {},
  photoStatusFlag: false,
  fileStatusFlag: false,
  tableColumns: [],
  defaultValues: [],
  waterTestList: [],
  equipdata: {
    id: 0,
    detectCode: "",
    sampleTime: "",
    drainageTimeFrom: "",
    drainageTimeTo: "",
    sampleLocation: "",
    location: "",
    detectResultSummary: "",
    detectOrganization: "",
    testingFile: "",
    reportNumber: "",
    drainageVolume: "",
    testManufacturer: "",
    samplePerson: "",
    areaName: "",
    samplePersonId: null,
    responsiblePerson: "",
    responsiblePersonId: null,
    samplingPhoto: [],
    detectReportAttachment: [],
    manufactureDate: "",
    warrantyEndDate: "",
    updateTime: "",
    testItems: [],
    useDateFrom: [],
    testResult: {}
  },
  queryParams: {
    orderByColumn: "",
    isAsc: "",
    areaCode: "",
    multipleLocation: [],
    detectCode: "",
    samplePerson: "",
    samplePersonId: "",
    detectResultSummary: "",
    detectCategory: "PARTICLE",
    detectOrganization: "",
    reportNumber: "",
    timeFrom: "",
    timeTo: "",
    orderBy: "",
    pageNum: 1,
    pageSize: 20
  },
  rules: {
    sampleTime: [{ required: true, message: "取样时间不能为空", trigger: "change" }],
    useDateFrom: [{ required: true, message: "排水时段不能为空", trigger: "change" }],
    location: [{ required: true, message: "取样点不能为空", trigger: "change" }],
    // drainageVolume: [{ required: true, message: "排水量(m³)不能为空", trigger: "blur" }],
    testManufacturer: [{ required: true, message: "检测厂商不能为空", trigger: "blur" }],
    samplePerson: [{ required: true, message: "取样人不能为空", trigger: "blur" }],
    responsiblePerson: [{ required: true, message: "本科负责人不能为空", trigger: "blur" }]
  },
  headers: {
    Authorization: "Bearer " + getToken().accessToken || ""
  },
  moduleName: "",
  dialogImageUrl: "",
  imageVisible: false
});

const {
  liquidList,
  queryParams,
  tableColumns,
  defaultValues,
  form,
  rules,
  equipdata,
  waterTestList,
  equipmentTypeList,
  modelIdList,
  photoStatusFlag,
  fileStatusFlag
} = toRefs(data);

const checkTime = () => {
  if (equipdata.value.manufactureDate && equipdata.value.warrantyEndDate) {
    if (equipdata.value.manufactureDate > equipdata.value.warrantyEndDate) {
      PxMessage({
        message: "开始时间不能大于结束时间",
        type: "error"
      });
    }
  }
};

// 取样点
const getqueryCategoryList = () => {
  // queryChildByTypeCodeAndItemValue({
  //   value: "CSP01",
  //   typeCode: "MCTS"
  // }).then((response: any) => {
  //   //console.log(response);
  //   liquidList.value = response;
  // });
  //销售单位
  queryChildByTypeCodeAndItemValue({
    value: "SU01",
    typeCode: "WTTS"
  }).then((response: any) => {
    //console.log(response);
    testList.value = response;
  });
};
const resetTable = time => {
  dateRange.value = time ? time : [];
  getList();
};

const getList = () => {
  queryParams.value.timeFrom = dateRange.value[0];
  queryParams.value.timeTo = dateRange.value[1];
  loading.value = true;
  wasteWaterqueryListPage0(queryParams.value)
    .then((response: any) => {
      typeList.value = response.data;
      total.value = response.total;
      loading.value = false;
    })
    .catch(error => {
      loading.value = false;
    });
};

/** 取消按钮 */
function cancel() {
  equipopen.value = false;
  showCharts.value = true;
}
function equipopenDetailcancel() {
  equipopenDetail.value = false;
  showCharts.value = true;
}
/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    dictionaryName: undefined,
    dictionaryType: undefined,
    status: "VALID",
    remarks: undefined
  };
  proxy.resetForm("dictRef");
}
/** 搜索按钮操作 */
function handleQuery(type) {
  if (type == "search") {
    queryParams.value.pageNum = 1;
  }
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    samplePerson: "",
    detectResultSummary: "",
    detectOrganization: "",
    reportNumber: "",
    detectCode: "",
    areaCode: "",
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    samplePersonId: "",
    detectCategory: "PARTICLE",
    orderByColumn: "",
    isAsc: "",
    multipleLocation: [],
    timeFrom: "",
    timeTo: "",
    orderBy: ""
  };
  dateRange.value = [];
  showCharts.value = true;
  handleQuery("reset");
}
/** 搜索按钮操作 */
function handleQueryCharts(type) {
  if (type == "search") {
  }
  getList();
}
/** 重置按钮操作 */
function resetQueryCharts() {
  dateRangeCharts.value = [];
  handleQueryCharts("reset");
}

/** 新增按钮操作 */
function handleAdd() {
  buttonTitle.value = "新增";
  jibenxinxiFlg.value = true;
  jiqicanshuFlg.value = true;
  shebeitaizhangFlg.value = true;
  moxingshezhiFlg.value = true;
  equipopenDetail.value = true;
  fromdisable.value = false;
  equipmentTypeList.value = [];
  modelIdList.value = [];
  equipdata.value = {
    id: null,
    detectCode: "",
    sampleTime: "",
    drainageTimeFrom: "",
    drainageTimeTo: "",
    sampleLocation: "",
    testingFile: "",
    location: "",
    detectResultSummary: "",
    detectOrganization: "",
    reportNumber: "",
    drainageVolume: "",
    testManufacturer: "",
    samplePerson: "",
    areaName: "",
    samplePersonId: "",
    responsiblePerson: "",
    responsiblePersonId: "",
    samplingPhoto: [],
    detectReportAttachment: [],
    manufactureDate: "",
    updateTime: "",
    warrantyEndDate: "",
    testItems: [],
    useDateFrom: [],
    testResult: {}
  };
  wasteWatergetTestItem0({ detectCategory: "PARTICLE" }).then((response: any) => {
    console.log(response);
    waterTestList.value = response;
    response.forEach(item => {
      equipdata.value.testResult[item.key] = "";
    });
    console.log(equipdata.value.testResult);
  });
}
const handleDetail = async val => {
  jibenxinxiFlg.value = true;
  jiqicanshuFlg.value = true;
  shebeitaizhangFlg.value = true;
  moxingshezhiFlg.value = true;
  const data: any = await wasteWaterqueryDetail0({ id: val, extra: "PARTICLE" });
  //console.log(data);

  equipopen.value = true;
  // equipopenDetail.value = true;
  fromdisable.value = true;
  equipdata.value = data;
  equipdata.value.useDateFrom = [data?.drainageTimeFrom, data?.drainageTimeTo];
  if (data?.samplingPhoto && data?.samplingPhoto.length > 0) {
    data?.samplingPhoto.forEach(item => {
      item.url = item.fileUrl;
      item.name = item.originalName;
    });
    equipdata.value.samplingPhoto = data?.samplingPhoto;
  } else {
    equipdata.value.samplingPhoto = [];
  }
  if (data.detectReportAttachment && data.detectReportAttachment.length > 0) {
    data.detectReportAttachment.forEach(item => {
      item.url = item.fileUrl;
      item.name = item.originalName;
    });
    equipdata.value.detectReportAttachment = data.detectReportAttachment;
  } else {
    equipdata.value.detectReportAttachment = [];
  }
  const objval = {};
  data.testItems.forEach(item => {
    objval[item.key] = item.testValue;
    item.testBtn = false;
  });
  equipdata.value.testResult = objval;
  showCharts.value = false;
};

const handleEditor = async val => {
  buttonTitle.value = "编辑";
  jibenxinxiFlg.value = true;
  jiqicanshuFlg.value = true;
  shebeitaizhangFlg.value = true;
  moxingshezhiFlg.value = true;

  const data: any = await wasteWaterqueryDetail0({ id: val, extra: "PARTICLE" });
  // console.log(data);
  equipopenDetail.value = true;
  fromdisable.value = false;
  equipdata.value = data;
  equipdata.value.samplePersonId = data.samplePersonId ? Number(data.samplePersonId) : null;
  equipdata.value.responsiblePersonId = data.responsiblePersonId ? Number(data.responsiblePersonId) : null;
  equipdata.value.location = data.sampleLocation;
  equipdata.value.useDateFrom = [data?.drainageTimeFrom, data?.drainageTimeTo];
  if (data?.samplingPhoto && data?.samplingPhoto.length > 0) {
    data?.samplingPhoto.forEach(item => {
      item.url = item.fileUrl;
      item.name = item.originalName;
    });
    equipdata.value.samplingPhoto = data?.samplingPhoto;
  } else {
    equipdata.value.samplingPhoto = [];
  }
  if (data.detectReportAttachment && data.detectReportAttachment.length > 0) {
    data.detectReportAttachment.forEach(item => {
      item.url = item.fileUrl;
      item.name = item.originalName;
    });
    equipdata.value.detectReportAttachment = data.detectReportAttachment;
  } else {
    equipdata.value.detectReportAttachment = [];
  }
  const objval = {};
  data.testItems.forEach(item => {
    objval[item.key] = item.testValue;
  });
  equipdata.value.testResult = objval;
};
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
// 新的图片列表
const changePhotoList1 = val => {
  equipdata.value.samplingPhoto = val;
};

// 新的文件列表
const changeFileList = val => {
  equipdata.value.testingFile = val;
};

const submitHandler = async () => {
  const message = "上传成功";
  PxMessage.success(message);
  await getList();
};

/** 提交按钮 */

const equipopenDetailsubmitForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      const params = {
        id: equipdata.value.id,
        detectCategory: "PARTICLE",
        detectCode: equipdata.value.detectCode,
        sampleTime: equipdata.value.sampleTime,
        drainageTimeFrom: equipdata.value.useDateFrom[0],
        drainageTimeTo: equipdata.value.useDateFrom[1],
        sampleLocation: equipdata.value.location,
        drainageVolume: equipdata.value.drainageVolume,
        testManufacturer: equipdata.value.testManufacturer,
        samplePerson: equipdata.value.samplePerson,
        samplePersonId: equipdata.value.samplePersonId,
        responsiblePerson: equipdata.value.responsiblePerson,
        responsiblePersonId: equipdata.value.responsiblePersonId,
        samplingPhoto: equipdata.value.samplingPhoto,
        detectOrganization: equipdata.value.detectOrganization,
        detectResultSummary: equipdata.value.detectResultSummary,
        detectReportAttachment: equipdata.value.detectReportAttachment,
        testResult: equipdata.value.testResult,
        updateTime: equipdata.value.updateTime
      };
      if (buttonTitle.value == "新增") {
        if (params.samplingPhoto.length > 0) {
          params.samplingPhoto = params.samplingPhoto.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        }
        if (params.detectReportAttachment.length > 0) {
          params.detectReportAttachment = params.detectReportAttachment.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        }
        wasteWateradd0(params).then((response: any) => {
          PxMessage({
            message: `${buttonTitle.value == "新增" ? "添加成功" : "修改成功"}`,
            type: "success"
          });
          resetQuery();
          equipopenDetail.value = false;
        });
      } else {
        if (params.samplingPhoto.length > 0) {
          params.samplingPhoto = params.samplingPhoto.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        }
        if (params.detectReportAttachment.length > 0) {
          params.detectReportAttachment = params.detectReportAttachment.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        }
        wasteWaterupdate0(params).then((response: any) => {
          PxMessage({
            message: `${buttonTitle.value == "新增" ? "添加成功" : "修改成功"}`,
            type: "success"
          });
          resetQuery();
          equipopenDetail.value = false;
        });
      }
    }
  });
};
/** 删除按钮操作 */
function handleDelete(row) {
  //console.log(row);
  // const dictIds = [];
  // if (row.equipmentId != undefined) {
  //   dictIds.push(row.equipmentId);
  // } else {
  //   dictIds.push(...ids.value);
  // }
  PxMessageBox.confirm('是否确认删除"' + row.detectCode + '"？', "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const data = await wasteWaterdelete0({ id: row.id });
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
    })
    .catch(() => {});
}

// 分析
const analyze = (data, row: any) => {
  data.forEach((item, index) => {
    if (item.itemName == row.itemName) {
      data[index].testBtn = true;
    } else {
      data[index].testBtn = false;
    }
  });
  initSpc(row);
};

const spcOptions = ref({});
const midKey = ref(Date.now());

let chartsInstance = null;
const barChartsRef = ref(null);
const initSpc = async (el: any) => {
  console.log(equipdata.value.location, equipdata.value);
  const title = "Particle检测结果与在线监测数据对照";
  const param = {
    // facCode: "FAC_83abf9",
    className: "MACHINE",
    zones: [getZone(equipdata.value.sampleLocation)], // checkAreaList.value
    detectDate: equipdata.value.sampleTime.split(" ")[0],
    // detectDate: "2024-12-03",
    types: [el.itemAttribute],
    requestId: ""
  };
  const res: any = await getDetectedValuesInPair(param);
  let arr = [["product", "Q部门", "online检测", "Ai预测"]];
  res.forEach(item => {
    arr.push([item.sampleSpec, Number(item.sampleValueQ), Number(item.sampleValueR), Number(item.sampleValueRAi)]);
  });
  let legendData = res.map(item => item.sampleSpec);
  const data = { arr, legendData };
  const options: UtilsEChartsOption = {
    color: ["#4786FF", "#14C7C7", "#FCD34D"],
    title: {
      text: title,
      textStyle: {
        fontSize: 16
      },
      // subtext: "曲线标题",
      left: "left",
      top: "top",
      padding: [10, 0, 0, 20]
    },
    tooltip: {
      trigger: "axis",
      confine: true,
      axisPointer: {
        type: "shadow"
      }
    },
    legend: {
      type: "scroll",
      // pager: {
      //   orient: "vertical",
      //   pageButtonItemGap: 5
      // },
      // data: props.areaList.map((item: any) => item.name),
      // data: data.legendData,
      orient: "horizontal",
      bottom: "0"
    },
    grid: {
      left: "24px",
      top: "15%",
      right: "24px",
      bottom: "5%",
      containLabel: true
    },
    dataset: {
      source: data.arr
    },
    xAxis: {
      type: "category"
      // data: ["12:00", "13:00", "14:00", "15:00", "16:00"]
    },
    yAxis: [
      {
        type: "value",
        // name: `单位`,
        alignTicks: true,
        axisLine: {
          lineStyle: {
            width: 2
          }
        }
      }
    ],
    series: [
      {
        type: "bar",
        barWidth: 16,
        itemStyle: {
          color: "#4786FF"
        },
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        }
      },
      {
        type: "bar",
        barWidth: 16,
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        itemStyle: {
          color: "#14C7C7"
        }
      },
      {
        type: "bar",
        barWidth: 16,
        emphasis: {
          focus: "series",
          blurScope: "coordinateSystem"
        },
        itemStyle: {
          color: "#FCD34D"
        }
      }
    ]
  };
  showBarCharts.value = true;
  if (showBarCharts.value) {
    nextTick(() => {
      if (barChartsRef.value) {
        chartsInstance = markRaw(echarts.init(barChartsRef.value));
        chartsInstance.setOption(options);
        window.addEventListener("resize", handelResize);
        // window.addEventListener("resize", handelResize);
        chartsInstance.resize();
        const arr1 = [getZone(equipdata.value.sampleLocation)];
        const arr2 = [res[0].sampleSpec];
        getQdata(arr1, arr2); // 默认展示第一个区域的spc
        chartsInstance.on("click", params => {
          console.log(params, "9999999999999999");
          currentBar.value = params.seriesName;
          if (params.seriesName === "Q部门") {
            getQdata(arr1, arr2);
          } else {
            getOnePoint(arr1, arr2);
          }
        });
      }
    });
  }
};

const getZone = val => {
  const arr = liquidList.value.filter(el => el.itemValue === val);
  if (arr && arr.length) {
    return arr[0].itemDesc || val;
  } else {
    return val;
  }
};

const handelResize = () => {
  if (chartsInstance) {
    chartsInstance.resize();
  }
};

const formatDate = timestamp => {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = (date.getMonth() + 1).toString().padStart(2, "0");
  const day = date.getDate().toString().padStart(2, "0");
  const h = date.getHours().toString().padStart(2, "0");
  const m = date.getMinutes().toString().padStart(2, "0");
  const s = date.getSeconds().toString().padStart(2, "0");
  return `${year}-${month}-${day} ${h}:${m}:${s}`;
};

const getQdata = async (array1, array2) => {
  const params = {
    zones: array1,
    types: array2,
    startTime: proxy.parseTime(new Date(equipdata.value.sampleTime).getTime() - 12 * 60 * 60 * 1000, "{y}-{m}-{d} {h}:{i}:{s}"), // equipdata.value.sampleTime
    endTime: proxy.parseTime(new Date(equipdata.value.sampleTime).getTime() + 12 * 60 * 60 * 1000, "{y}-{m}-{d} {h}:{i}:{s}")
  };
  const res: any = await queryQCheck(params);
  console.log(res);
  let spcList = [];
  if (res[0] && Object.keys(res[0]).length) {
    spcList =
      (Object.keys(res[0]).length &&
        Object.keys(res[0]).map(e => {
          return {
            indicatorName: e,
            pointValues: res[0][e].map(item => {
              return {
                time: item.dateTimeResult,
                ...item
              };
            })
          };
        })) ||
      [];
  }
  if (!spcList.length) {
    costOptions.value = {};
    return;
  }
  const obj: any = spcList[0];
  const yAxis =
    spcList &&
    spcList.map((item, index) => {
      return {
        type: "value",
        // name: obj.indicatorName,
        // nameLocation: "middle", //居中
        offset: (0 + index) * 90,
        // nameGap: 70, //轴线距离
        // nameRotate: 90, //字体选择角度
        axisLine: {
          show: true,
          lineStyle: {
            type: "solid"
          }
        }
      };
    });
  const series =
    spcList &&
    spcList.map((e, ind) => {
      return {
        // data: [400, 400, 400, 400, 400, 400],
        data: e.pointValues.length > 0 ? e.pointValues.map(item => Number(item.value)) : [],
        type: "line",
        name: e.indicatorName,
        yAxisIndex: ind
        // areaStyle: {
        //   opacity: 0.15
        // },
        // symbol: "none"
        // markLine: {
        //   symbol: "none",
        //   data: [
        //     {
        //       name: "USL值",
        //       yAxis: Number(e.uslValue),
        //       lineStyle: {
        //         color: "#A600FF",
        //         wideh: "1",
        //         type: "solide"
        //       },
        //       label: {
        //         position: "insideEndTop",
        //         formatter: `USL值${e.uslValue}`,
        //         color: "#A600FF",
        //         fontWeight: 600
        //       }
        //     },
        //     {
        //       name: "UCL值",
        //       yAxis: Number(e.uclValue),
        //       lineStyle: {
        //         color: "#FF0000",
        //         wideh: "1",
        //         type: "dashed"
        //       },
        //       label: {
        //         position: "insideEndTop",
        //         formatter: `UCL值${e.uclValue}`,
        //         color: "#FF0000",
        //         fontWeight: 600
        //       }
        //     },
        //     {
        //       name: "UWL值",
        //       yAxis: Number(e.uwlValue),
        //       lineStyle: {
        //         color: "#FF9900",
        //         wideh: "1",
        //         type: "dashed"
        //       },
        //       label: {
        //         position: "insideEndTop",
        //         formatter: `UWL值${e.uwlValue}`,
        //         color: "#FF9900",
        //         fontWeight: 600
        //       }
        //     },
        //     {
        //       name: "Target值",
        //       yAxis: Number(e.targetValue),
        //       lineStyle: {
        //         color: "#00E272",
        //         wideh: "1",
        //         type: "solide"
        //       },
        //       label: {
        //         position: "insideEndTop",
        //         formatter: `Target值${e.targetValue}`,
        //         color: "#00E272",
        //         fontWeight: 600
        //       }
        //     },
        //     {
        //       name: "LWL值",
        //       yAxis: Number(e.lwlValue),
        //       lineStyle: {
        //         color: "#FF9900",
        //         wideh: "1",
        //         type: "dashed"
        //       },
        //       label: {
        //         position: "insideEndTop",
        //         formatter: `LWL值${e.lwlValue}`,
        //         color: "#FF9900",
        //         fontWeight: 600
        //       }
        //     },
        //     {
        //       name: "LCL值",
        //       yAxis: Number(e.lclValue),
        //       lineStyle: {
        //         color: "#FF0000",
        //         wideh: "1",
        //         type: "dashed"
        //       },
        //       label: {
        //         position: "insideEndTop",
        //         formatter: `LCL值${e.lclValue}`,
        //         color: "#FF0000",
        //         fontWeight: 600
        //       }
        //     },
        //     {
        //       name: "LSL值",
        //       yAxis: Number(e.lslValue),
        //       lineStyle: {
        //         color: "#A600FF",
        //         wideh: "1",
        //         type: "solide"
        //       },
        //       label: {
        //         position: "insideEndTop",
        //         formatter: `LSL值${e.lslValue}`,
        //         color: "#A600FF",
        //         fontWeight: 600
        //       }
        //     }
        //   ]
        // }
      };
    });
  const legendData = spcList && spcList.map(item => item.indicatorName);
  const option = {
    color: "#ccc",
    grid: {
      left: "30px",
      top: "40px",
      right: "0",
      bottom: "5%",
      containLabel: true
    },
    legend: {
      type: "scroll",
      pager: {
        orient: "vertical",
        pageButtonItemGap: 5
      },
      data: legendData,
      orient: "horizontal",
      bottom: "0"
    },
    tooltip: {
      trigger: "axis",
      confine: true
    },
    xAxis: {
      type: "category",
      boundarGap: false,
      data: obj.pointValues.length > 0 ? obj.pointValues.map(item => formatDate(item.time)) : ["11:00", "12:00", "13:00", "14:00", "15:00", "16:00"]
    },
    yAxis: yAxis,
    series: series
  };
  costOptions.value = option;
  tablePieKey.value = Date.now();
};

const getOnePoint = async (array1, array2) => {
  const obj = {
    zones: array1,
    types: array2,
    factory: {
      id: 1,
      parentCode: "",
      code: "",
      name: "",
      type: "",
      path: "",
      // facCode: "FAC_83abf9",
      principalId: 1,
      principalName: "",
      className: "MACHINE",
      children: [
        {
          id: 1,
          parentCode: "",
          code: "",
          name: "",
          type: "",
          path: "",
          // facCode: "",
          principalId: 1,
          principalName: "",
          className: ""
        }
      ]
    },
    requestId: ""
  };
  const pointObj: any = await getReadersInZoneByType(obj);
  let arr = [];
  if (Object.keys(pointObj) && Object.keys(pointObj).length > 0) {
    Object.keys(pointObj).forEach(el => {
      arr.push(pointObj[el]);
    });
  }
  if (!arr.length) return;
  const params = {
    pointList: [...arr],
    timePeriod: "hour",
    startTime: proxy.parseTime(new Date(equipdata.value.sampleTime).getTime() - 12 * 60 * 60 * 1000, "{y}-{m}-{d} {h}:{i}:{s}"), // equipdata.value.sampleTime
    endTime: proxy.parseTime(new Date(equipdata.value.sampleTime).getTime() + 12 * 60 * 60 * 1000, "{y}-{m}-{d} {h}:{i}:{s}")
  };
  const res: any = await spcquerySpcAnalysis(params);
  const spcList =
    res.length &&
    res.map((item: any) => {
      item.startTime = proxy.parseTime(new Date(equipdata.value.sampleTime).getTime() - 12 * 60 * 60 * 1000, "{y}-{m}-{d} {h}:{i}:{s}");
      item.endTime = proxy.parseTime(new Date(equipdata.value.sampleTime).getTime() - 12 * 60 * 60 * 1000, "{y}-{m}-{d} {h}:{i}:{s}");
      item.pointValues = item.pointValues ? item.pointValues : []; // null时判断，有数据可放开
      return {
        ...item
      };
    });
  spcOptions.value = spcList[0] || {};
  midKey.value = Date.now();
};

// 导入
const handleUpload = () => {
  dialogVisible.value = true;
};
/** 导出按钮操作 */
function handleExport() {
  if (ids.value.length < 1) {
    PxMessage({
      type: "warning",
      message: "请至少选择一条数据"
    });
    return;
  }
  const params = {
    ids: [...ids.value],
    extra: "PARTICLE"
  };
  proxy.download("post", "/operation/api/v1/machine/detect/amc/export", params, "洁净室环境检测-PARTICLE.xlsx");
}
</script>
<style scoped lang="scss">
.page-contain {
  padding: 16px 24px;
  background-color: white;
}

.page-chart {
  width: 100%;
  height: 450px;
  background-color: white;
}

.addEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.editorEquip {
  position: absolute;
  top: 0;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.btn_box {
  width: 100%;
  padding: 0 20px 16px;

  .btn_chart {
    display: flex;
    flex-flow: row nowrap;
    gap: 16px;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    min-width: 1300px;

    .chart_item {
      width: 50%;
      height: 480px;

      .echarts-empty {
        display: flex;
        justify-content: center;
        width: 100%;
        height: 480px;
        margin: auto;
        border: 1px solid #dcdcdc;
      }

      .echarts-empty1 {
        display: flex;
        justify-content: center;
        width: 100%;
        height: 480px;
        margin: auto;
      }
    }
  }
}

.px-dialog-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 2002;
  width: 100%;
  height: 50px;
  padding-top: 10px;
  padding-right: 34px;
  text-align: right;
  background: white;
  box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
}

.card-header {
  min-height: 40px;
  padding: 14px 15px 7px !important;
  cursor: pointer;
  user-select: none;
  background: #e7eefb;
}

.card-title {
  float: left;
  line-height: 14px;
}

.card-main {
  float: left;
  margin: -3px 8px 0 5px;
  cursor: pointer;
}

.box-card1 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card2 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card3 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card4 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.demo-form-inline {
  .px-input {
    --px-input-width: calc(100% - 100px);
  }

  .px-form-item {
    width: 100%;
  }

  .px-textarea__inner {
    width: calc(100% - 100px) !important;
  }

  .px-form-item__label {
    font-weight: 400 !important;
  }
}

.form-div {
  padding: 24px;

  .px-row {
    margin-bottom: 16px;
  }
}

.px-icon {
  font-size: 16px !important;
}

:deep(.px-tabs--top .px-tabs__item.is-top.is-active) {
  border: none;

  .pane-bottom {
    line-height: 30px;
    border-bottom: 2px solid #3b82f6;
  }
}

:deep(.px-tabs .px-tabs__item) {
  .pane-bottom {
    line-height: 30px;
  }
}

.pane-line {
  position: absolute;
  top: 12px;
  right: 0;
  height: 15px;
  color: #dcdcdc;
  border-left: 1px solid #dcdcdc;
}

.filename {
  position: absolute;
  bottom: -30px;
  width: 96px;
  overflow: hidden;
  color: rgb(166 167 172);
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.px-descriptions__label.px-descriptions__cell.is-bordered-label) {
  width: 166px;
  background: #e7eefb;
  border: 1px solid #dfdfdf;
}

:deep(.px-descriptions__body .px-descriptions__table.is-bordered .px-descriptions__cell) {
  border: 1px solid #dfdfdf;
}

.cell-item {
  text-align: right;
}

:deep(.px-table__header) {
  thead {
    tr {
      background-color: #e7eefb !important;

      th {
        font-size: 13px;
        font-weight: bold;
        color: #000;
        background-color: #e7eefb !important;
      }
    }
  }
}

:deep(.px-table--isfixedHeader .px-table__header-wrapper .px-table-fixed-column--right) {
  background-color: #e7eefb !important;
}

.center2 {
  :deep(.px-descriptions__body) {
    table {
      border-left: none;

      .is-bordered-label {
        border-left: none !important;
      }

      // .is-bordered-content {
      //   border-right: none !important;
      // }
    }
  }
}

.tableTop {
  display: flex;
  background-color: #e7eefb !important;
  border-right: 1px solid #dfdfdf;

  .topList {
    flex: 1;
    padding: 6px;
    font-size: 13px;
    font-weight: bold;
    line-height: 23px;
    color: #000;
    border: 1px solid #dfdfdf;
    border-right: none;
  }
}

.tableMain {
  display: flex;
  border-right: 1px solid #dfdfdf;

  .topList {
    flex: 1;
    padding: 6px;
    font-size: 13px;
    line-height: 23px;
    color: #000;
    border: 1px solid #dfdfdf;
    border-top: none;
    border-right: none;
  }
}

.btmContent {
  display: flex;
  gap: 16px;
  align-items: center;
  justify-content: flex-start;
  padding: 0 24px 16px;

  .queryBtn {
    display: flex;
    align-items: center;
    justify-content: flex-start;
  }
}

.btnSpc {
  padding: 0 20px 20px;
}
</style>
